

package com.starbaba.mall.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.FormData;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.jumai.server.common.util.ApiHost;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.mall.service.ProductItemService;
import com.starbaba.model.db.Short_Link;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.model.utils.ZipUtil;
import com.starbaba.tools.sequence.IntUtil;
import com.starbaba.tools.sequence.Sequence;
import com.tuanzi.server.loan_base.model.bean.mall.SmallImgOfItem;
import com.tuanzi.server.loan_base.model.bean.mall.TbkItem;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class ProductItemAction extends BaseAction implements ModelDriven<Loan_Mall_Item> {

	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
	//短链前缀
	private static final String SHORT_URL_PRE = ApiHost.getExternalHost() + "/share_service/redirect?from=";
	
	private Loan_Mall_Item model;
	private ProductItemService service;
	
	@Autowired
	@Qualifier("productItemServiceImpl")
	public void setService(ProductItemService service) {
		this.service = service;
	}
	
	/**
	 * 实时刷新商品库数据
	 * @throws Exception 
	 */
	public void refreshItem() throws Exception{
		String url = ApiHost.getExternalHost() + "/loan_mall_service/common?funid=3&rd=" + System.currentTimeMillis();
		JsonObject requestjson = new JsonObject();
		FormData formdata = new FormData();
		formdata.addParam("handle", "0");
		formdata.addParam("data", requestjson.toString());
		formdata.addParam("shandle", "1");
		PostData postData = new PostData(formdata);
		HttpResult httpResult = HttpClientUtil.post(url, postData);
		String responsedata = ZipUtil.unCompressData(httpResult.getData());
		JsonParser parser = new JsonParser();
		JsonObject responseJson = parser.parse(responsedata).getAsJsonObject();
		JsonObject resultObject = responseJson.getAsJsonObject("result");
		int status = resultObject.getAsJsonPrimitive("status").getAsInt();
		
		JsonObject result = new JsonObject();
		if(status == 1){
			result.addProperty("status", 1);
			LogService.info("实时更新返利商品库成功！！！");
		}else{
			result.addProperty("status", 0);
			LogService.info("实时更新返利商品库失败！！！");
		}
		
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void copyShortLink() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject result = new JsonObject();
		
		String itemId = (String) paramsMap.get("itemId");
		String selectSql = "select * from loan_mall_item i where i.id = ?";
		Loan_Mall_Item item = dao.get(selectSql, Loan_Mall_Item.class, itemId);
		
		String shortLinkUrl = item.getShort_url();
		if(StringUtils.isEmpty(shortLinkUrl)){
			Short_Link link = new Short_Link();
			Long id = Sequence.getSequence();
			//随机生成短链
			String shortLink = IntUtil.couponGen(id, 5);
			link.setId(id);
			link.setMemo("返利生成短链接");
			link.setUrl(item.getClick_url());
			link.setCtime(new Date());
			link.setLink_type("返利短链");
			link.setUnit_price(1f);
			link.setActivity("返利短链");
			link.setShort_link(shortLink);
			dao.add(link);
			
			//完整短链url
			shortLinkUrl = SHORT_URL_PRE+shortLink;
			item.setShort_url(shortLinkUrl);
			dao.update(item, "id");
		}
		result.addProperty("shortLink", shortLinkUrl);
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 上下线
	 */
	public void onOrOffline(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject result = new JsonObject();
		
		String itemId = (String) paramsMap.get("itemId");
		String status = (String) paramsMap.get("status");
		String selectSql = "select * from loan_mall_item i where i.id = ?";
		String updateSql = "UPDATE loan_mall_item SET status = ? WHERE id = ?";
		try {
			Loan_Mall_Item item = dao.get(selectSql, Loan_Mall_Item.class, itemId);
			if("1".equals(status)){  // 上线切换为下线状态
				dao.update(updateSql, 0,itemId);
				result.addProperty("status", "1");
				result.addProperty("message", "已成功下线");
			} else { // 下线切换为上线状态
				int sourceStatus = item.getSource_status();
				if(sourceStatus == 1){ // 只有联盟商品状态为有效时，才能切换有上线
					dao.update(updateSql, 1,itemId);
					result.addProperty("status", "1");
					result.addProperty("message", "已成功上线");
				} else {
					result.addProperty("status", "0");
					result.addProperty("message", "联盟商品已失效，不能上线");
				}
			}
		} catch (AppException e) {
			result.addProperty("status", "-1");
			result.addProperty("message", "服务器异常");
			LogService.error(e);
		} finally {
			try {
				sendJsonMessage(result.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public String show(){
		return "success";
	}
	
	public void queryList(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List list = service.getDateList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void saveItem(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject result = new JsonObject();
		try {
			File imgFile = model.getMainImgFile();
			if(imgFile != null){
				String imgUrl = uploadToQiniu(imgFile);
				model.setImg(imgUrl);
			}
			
			File introductionTopicImgFile = model.getIntroductionTopicImgFile();
			if(introductionTopicImgFile != null){
				String introductionTopicImgUrl = uploadToQiniu(introductionTopicImgFile);
				model.setIntroduction_topic_img(introductionTopicImgUrl);
			}
			
			model.setOptime(new Date());
			if(model.getFanli_amout() == null){
				model.setFanli_amout(0.0f);
			}
			dao.update(model, "id");
			result.addProperty("status", "1");
		} catch (Exception e) {
			result.addProperty("status", "0");
			LogService.error(e);
			e.printStackTrace();
		} finally {
			try {
				sendJsonMessage(result.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String editItem() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String sql = "SELECT * from loan_mall_item i WHERE i.id = ?";
		Loan_Mall_Item mallItem = dao.get(sql, Loan_Mall_Item.class, itemId);
		paramsMap.put("mallItem", mallItem);
		
		//源数据
		String smallImgJson = mallItem.getItem_text();
		TbkItem tbkItem = JSONUtils.fromJsonNew(smallImgJson, TbkItem.class);
		paramsMap.put("sourceData", tbkItem);
		
		SmallImgOfItem smallImgs = tbkItem.small_images;
		List<String> smallImgList = smallImgs.string;
		paramsMap.put("smallImgList", smallImgList);
		
		return "success";
	}
	 
	public String uploadToQiniu(File srcFile) {
		String iconUrl = null;
		if (srcFile.isDirectory()) {
			return iconUrl;
		} else {
			try {
				FileInputStream in = new FileInputStream(srcFile);
				// Zone为七牛机房所在地，根据源所在机房配置
		        Configuration config = new Configuration(Zone.zone0()); 
				iconUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
		        in.close();
			} catch (Exception e) {
				e.printStackTrace();
				LogService.error(e);
			}
		}
		return iconUrl;
	}
	
	@Override
	public Loan_Mall_Item getModel() {
		if (model == null) {
			model = new Loan_Mall_Item();
		}
		return model;
	}

}
















